﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Chbl.DAL;
using Chbl.Models;
using Chbl.Scheduling;

namespace Chbl.Controllers.AdminRole
{
    [Authorize(Roles = "admin")]
    public class AdminSeasonDivisionController : Controller
    {
        private readonly ChblDb _db;

        public AdminSeasonDivisionController(ChblDb db)
        {
            _db = db;
        }

        //
        // GET: /AdminSeasonDivision/

        public ViewResult Index()
        {
            var seasondivisions = _db.SeasonDivisions.Include(s => s.Season).Include(s => s.Division);
            return View(seasondivisions.ToList());
        }

        //
        // GET: /AdminSeasonDivision/Details/5

        public ViewResult Details(int id)
        {
            SeasonDivision seasondivision = _db.SeasonDivisions.Find(id);
            return View(seasondivision);
        }

        //
        // GET: /AdminSeasonDivision/Create

        public ActionResult Create()
        {
            ViewBag.SeasonId = new SelectList(_db.Seasons, "SeasonId", "Number");
            ViewBag.DivisionId = new SelectList(_db.Divisions, "DivisionId", "Name");
            return View();
        } 

        //
        // POST: /AdminSeasonDivision/Create

        [HttpPost]
        public ActionResult Create(SeasonDivision seasondivision)
        {
            if (ModelState.IsValid)
            {
                _db.SeasonDivisions.Add(seasondivision);
                _db.SaveChanges();
                return RedirectToAction("Index");  
            }

            ViewBag.SeasonId = new SelectList(_db.Seasons, "SeasonId", "SeasonId", seasondivision.SeasonId);
            ViewBag.DivisionId = new SelectList(_db.Divisions, "DivisionId", "Name", seasondivision.DivisionId);
            return View(seasondivision);
        }
        
        //
        // GET: /AdminSeasonDivision/Edit/5
 
        public ActionResult Edit(int id)
        {
            SeasonDivision seasondivision = _db.SeasonDivisions.Find(id);
            ViewBag.SeasonId = new SelectList(_db.Seasons, "SeasonId", "SeasonId", seasondivision.SeasonId);
            ViewBag.DivisionId = new SelectList(_db.Divisions, "DivisionId", "Name", seasondivision.DivisionId);
            return View(seasondivision);
        }

        //
        // POST: /AdminSeasonDivision/Edit/5

        [HttpPost]
        public ActionResult Edit(SeasonDivision seasondivision)
        {
            if (ModelState.IsValid)
            {
                _db.Entry(seasondivision).State = EntityState.Modified;
                _db.SaveChanges();
                return RedirectToAction("Index");
            }
            ViewBag.SeasonId = new SelectList(_db.Seasons, "SeasonId", "SeasonId", seasondivision.SeasonId);
            ViewBag.DivisionId = new SelectList(_db.Divisions, "DivisionId", "Name", seasondivision.DivisionId);
            return View(seasondivision);
        }

        //
        // GET: /AdminSeasonDivision/Delete/5
 
        public ActionResult Delete(int id)
        {
            SeasonDivision seasondivision = _db.SeasonDivisions.Find(id);
            return View(seasondivision);
        }

        //
        // POST: /AdminSeasonDivision/Delete/5

        [HttpPost, ActionName("Delete")]
        public ActionResult DeleteConfirmed(int id)
        {            
            SeasonDivision seasondivision = _db.SeasonDivisions.Find(id);
            _db.SeasonDivisions.Remove(seasondivision);
            _db.SaveChanges();
            return RedirectToAction("Index");
        }


        public ActionResult ConfirmCreateSchedule(int id)
        {
            SeasonDivision seasonDivision = _db.SeasonDivisions.Find(id);
            return View(seasonDivision);
        }

        [HttpPost, ActionName("ConfirmCreateSchedule")]
        public ActionResult ConfirmedCreateSchedule(int id)
        {
            SeasonDivision seasonDivision = _db.SeasonDivisions.Find(id);
            if (seasonDivision.Teams == null || seasonDivision.Teams.Count() % 2 == 1)
            {
                ViewBag.ErrorMessage = "Количество команд должно быть четным и больше нуля, попробуйте добавить команды в дивизион";
                return View(seasonDivision);
            }
            return RedirectToAction("CreateSchedule", new {id});
        }

        //
        // GET: //AdminSeasonDivision/CreateSchedule
        public ActionResult CreateSchedule(int id)
        {
            SeasonDivision seasonDivision = _db.SeasonDivisions.Find(id);
            var scheduler = new Scheduler
                                {
                                    Teams = new List<ITeam>(seasonDivision.Teams),
                                    StartDate = DateTime.Now,
                                    TourIntervalInDays = 7
                                };

            TempData["seasonDivision"] = seasonDivision;
            return View(scheduler);

        }

        [HttpPost]
        public ActionResult CreateSchedule(Scheduler scheduler)
        {
            var seasonDivision = TempData["seasonDivision"] as SeasonDivision;
            scheduler.Teams = new List<ITeam>(seasonDivision.Teams);

            if (ModelState.IsValid  && scheduler.TeamsNumberNotEvenOrZero)
            {
                DeleteExistingGames(seasonDivision);
                var schedule = scheduler.Generate();
                foreach (var game in schedule.GamesList)
                {
                    _db.Games.Add(new Game
                                     {
                                      Date = game.Date,
                                      GameOrder = game.GameOrder,
                                      HomeTeamId = game.HomeTeam.Id,
                                      RoadTeamId = game.RoadTeam.Id,
                                      SeasonDivisionId =  seasonDivision.SeasonDivisionId,
                                      TourNumber = game.TourNumber
                                     });
                }
                _db.SaveChanges();
                return RedirectToAction("Index");
            }            
            return View(scheduler);
        }

        private void DeleteExistingGames(SeasonDivision seasonDivision)
        {
            var gamesToDelete = _db.Games.Where(g => g.SeasonDivision.SeasonDivisionId == seasonDivision.SeasonDivisionId);
            foreach (var game in gamesToDelete)
            {
                _db.Games.Remove(game);
            }
        }


        protected override void Dispose(bool disposing)
        {
            _db.Dispose();
            base.Dispose(disposing);
        }
    }
}